package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.entity.BasePersonInfo;
import com.hzeport.bgs22emduty.entity.ParamSmsPeople;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.enums.SmsEnum;
import com.hzeport.bgs22emduty.outbound.BasePersonInfoRepository;
import com.hzeport.bgs22emduty.outbound.ParamSmsPeopleRepository;
import com.hzeport.bgs22emduty.outbound.ParamSmsTemplateRepository;
import com.hzeport.bgs22emduty.service.ParamDictionaryService;
import com.hzeport.bgs22emduty.vo.ParamSmsTemplate.ParamSmsSaveVO;
import com.hzeport.bgs22emduty.vo.ParamSmsTemplate.ParamSmsTemplateListVO;
import com.hzeport.bgs22emduty.vo.ParamSmsTemplate.ParamSmsTemplateSaveVO;
import com.hzeport.bgs22emduty.vo.base.PageVO;
import com.hzeport.bgs22emduty.common.base.BaseEntity;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.entity.ParamSmsTemplate;
import com.hzeport.bgs22emduty.outbound.db.ParamSmsTemplateRepositoryImpl;
import com.hzeport.bgs22emduty.service.ParamSmsTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 参数表-短信模板表：
此表中存储，各种类型的短信模板信息
 *
 * @author code generator
 * @date 2022-12-02 11:21:59
 */
@Service
@Slf4j
public class ParamSmsTemplateServiceImpl extends BaseServiceImpl<ParamSmsTemplateRepositoryImpl, ParamSmsTemplate> implements ParamSmsTemplateService {

    @Resource
    private ParamSmsTemplateRepository paramSmsTemplateRepository;
    @Resource
    private ParamDictionaryService paramDictionaryService;
    @Resource
    private ParamSmsPeopleRepository smsPeopleRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;

    @Override
    public BaseResult<Page<ParamSmsTemplateListVO>> list(PageVO pageVO, UserInfoDetailVO userInfo) {
        Page<ParamSmsTemplate> page=paramSmsTemplateRepository.page(new Page(pageVO.getPageNum(),pageVO.getPageSize()),
                new LambdaQueryWrapper<ParamSmsTemplate>().eq(ParamSmsTemplate::getTemplateCode,userInfo.getCustomscode())
                        .orderByDesc(BaseEntity::getCreateTime));
        List<ParamSmsTemplateListVO> paramSmsTemplateListVOS=new ArrayList<>();
        for (ParamSmsTemplate paramSmsTemplate : page.getRecords()) {
            ParamSmsTemplateListVO paramSmsTemplateListVO = new ParamSmsTemplateListVO();
            paramSmsTemplateListVO.setId(paramSmsTemplate.getId());
            paramSmsTemplateListVO.setRemark(paramSmsTemplate.getRemark());
            paramSmsTemplateListVO.setTemplateCode(paramSmsTemplate.getTemplateCode());
            paramSmsTemplateListVO.setTemplateName(paramSmsTemplate.getTemplateName());
            paramSmsTemplateListVO.setParamDutyId(paramSmsTemplate.getParamDutyId());
            paramSmsTemplateListVO.setIsSend(paramSmsTemplate.getIsSend());
            paramSmsTemplateListVO.setSmsType(SmsEnum.getDescByCode( paramSmsTemplate.getSmsType() ));
            paramSmsTemplateListVOS.add(paramSmsTemplateListVO);
        }
        Page<ParamSmsTemplateListVO> listVOPage = new Page<>();
        listVOPage.setRecords(paramSmsTemplateListVOS);
        listVOPage.setTotal(page.getTotal());
        return BaseResult.ok(listVOPage,"查询成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult delete(String id,UserInfoDetailVO userInfo) {
        paramSmsTemplateRepository.removeById(id);
        return BaseResult.ok(null,"删除成功");
    }

    @Override
    public BaseResult<ParamSmsTemplateSaveVO> detail(String id) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "HH:mm:ss" );
        ParamSmsTemplateSaveVO vo = new ParamSmsTemplateSaveVO();
        ParamSmsTemplate smsTemplate = getById( id );

        BeanUtils.copyProperties( smsTemplate , vo );
        vo.setOverTime( smsTemplate.getSSendBefore() );
        vo.setDutyTypeString( smsTemplate.getDutyType() );

        if(!StringUtils.isEmpty( smsTemplate.getSSendTime() )) {
            vo.setSSendTime( smsTemplate.getSSendTime().format( formatter  ) );
        }
        // 短信提醒人员
        List< ParamSmsPeople > smsPeopleList = smsPeopleRepository.list( new LambdaQueryWrapper< ParamSmsPeople >()
                .eq( ParamSmsPeople::getSmsInfoId , smsTemplate.getId() ) );
        if( SmsEnum.SIGN_IN_EXCEPTION.getCode().equals( smsTemplate.getSmsType() ) || SmsEnum.SIGN_OUT_EXCEPTION.getCode().equals( smsTemplate.getSmsType() )) {
            vo.setSmsPeople( smsPeopleList.stream().map( ParamSmsPeople::getSmsReceiverNo ).collect( Collectors.toList()));
        }
        // 调班
        if(SmsEnum.ADJUST_REMID.getCode().equals( smsTemplate.getSmsType() ) ){
            vo.setSmsPeople( smsPeopleList.stream().map( ParamSmsPeople::getType ).collect( Collectors.toList()));
        }
        return BaseResult.ok(vo);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveData(ParamSmsTemplateSaveVO dto, UserInfoDetailVO userInfo) throws Exception {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "HH:mm:ss" );
        if(StringUtils.isEmpty( dto.getSmsType() )){
            return BaseResult.failed("短信类型不能为空");
        }
        if(StringUtils.isEmpty( dto.getIsSend() )){
            return BaseResult.failed("是否发送短信不能为空");
        }
        if(StringUtils.isEmpty( dto.getRemark() )){
            return BaseResult.failed("短信内容不能为空");
        }
        ParamSmsTemplate smsTemplate = new ParamSmsTemplate();
        BeanUtils.copyProperties( dto , smsTemplate );
        if(!StringUtils.isEmpty( dto.getSSendTime() )){
            smsTemplate.setSSendTime( LocalTime.parse( dto.getSSendTime() , formatter  ));
        }
        smsTemplate.setTemplateCode( userInfo.getCustomscode());
        smsTemplate.setTemplateName( userInfo.getCustomsName());
        smsTemplate.setUpdateBy( userInfo.getUserId());
        smsTemplate.setDutyType( dto.getDutyTypeString() );
        smsTemplate.setUpdateTime( LocalDateTime.now() );
        smsTemplate.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
        if(StringUtils.isEmpty( dto.getId() )){
            smsTemplate.setCreateBy( userInfo.getUserId());
            smsTemplate.setCreateTime( LocalDateTime.now() );
        }
        // 为签到签退类型时 超过时间为提前时间
        if( SmsEnum.SIGN_IN_EXCEPTION.getCode().equals( dto.getSmsType() ) || SmsEnum.SIGN_OUT_EXCEPTION.getCode().equals( dto.getSmsType() )){
            smsTemplate.setSSendBefore( dto.getOverTime() );
        }
//        paramSmsTemplateRepository.saveOrUpdate( smsTemplate );
        if(StringUtils.isEmpty(dto.getId())){
            paramSmsTemplateRepository.save(smsTemplate);
        }else {
            ParamSmsTemplate byId = paramSmsTemplateRepository.getById(dto.getId());
            if(byId != null){
                smsTemplate.setRecVersion(byId.getRecVersion());
                paramSmsTemplateRepository.updateById(smsTemplate);
            }
        }

        // 人员保存
        smsPeopleRepository.remove( new LambdaQueryWrapper< ParamSmsPeople >()
                .eq( ParamSmsPeople::getSmsInfoId , smsTemplate.getId() ) );

        List<ParamSmsPeople> smsPeoples = new ArrayList<>();
        if( !CollectionUtils.isEmpty( dto.getSmsPeople() ) ){
            for ( String smsPerson : dto.getSmsPeople() ) {
                ParamSmsPeople paramSmsPeople = new ParamSmsPeople();
                paramSmsPeople.setSmsInfoId( smsTemplate.getId() );
                paramSmsPeople.setUpdateBy( userInfo.getUserId());
                paramSmsPeople.setUpdateTime( LocalDateTime.now() );
                paramSmsPeople.setCreateBy( userInfo.getUserId());
                paramSmsPeople.setCreateTime( LocalDateTime.now() );
                paramSmsPeople.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
                // 签到签退
                BasePersonInfo personInfo = basePersonInfoRepository.getOne( new LambdaQueryWrapper< BasePersonInfo >()
                        .eq( BasePersonInfo::getUserno , smsPerson ) , false );
                paramSmsPeople.setSmsReceive( personInfo.getPhone() );
                paramSmsPeople.setSmsReceiverName( personInfo.getUsername() );
                paramSmsPeople.setSmsReceiverNo( personInfo.getUserno() );
                smsPeoples.add( paramSmsPeople );
            }
        }
        smsPeopleRepository.saveBatch( smsPeoples );
        return BaseResult.ok(null , "保存成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult< String > smsSwitch( ParamSmsTemplateSaveVO dto , UserInfoDetailVO userInfo ) {
        ParamSmsTemplate paramSmsTemplate = new ParamSmsTemplate();
        paramSmsTemplate.setUpdateBy(userInfo.getUserId());
        paramSmsTemplate.setUpdateTime(LocalDateTime.now());
        paramSmsTemplate.setId( dto.getId() );
        paramSmsTemplate.setIsSend( dto.getIsSend() );
        ParamSmsTemplate byId = getById(dto.getId());
        if(byId != null){
            paramSmsTemplate.setRecVersion(byId.getRecVersion());
        }
        updateById( paramSmsTemplate );
        return BaseResult.ok(null,"操作成功");
    }

    @Override
    public BaseResult saveZs( ParamSmsSaveVO dto , UserInfoDetailVO userInfo ) {
        if(StringUtils.isEmpty( dto.getSmsType() )){
            return BaseResult.failed("短信类型不能为空");
        }
        if(StringUtils.isEmpty( dto.getIsSend() )){
            return BaseResult.failed("是否发送短信不能为空");
        }
        if(StringUtils.isEmpty( dto.getRemark() )){
            return BaseResult.failed("短信内容不能为空");
        }
        ParamSmsTemplate smsTemplate = new ParamSmsTemplate();
        BeanUtils.copyProperties( dto , smsTemplate );
        smsTemplate.setTemplateCode( userInfo.getCustomscode());
        smsTemplate.setTemplateName( userInfo.getCustomsName());
        smsTemplate.setUpdateBy( userInfo.getUserId());
        smsTemplate.setUpdateTime( LocalDateTime.now() );
        smsTemplate.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
        if(StringUtils.isEmpty( dto.getId() )){
            smsTemplate.setCreateBy( userInfo.getUserId());
            smsTemplate.setCreateTime( LocalDateTime.now() );
        }
//        paramSmsTemplateRepository.saveOrUpdate( smsTemplate );
        if(StringUtils.isEmpty(dto.getId())){
            paramSmsTemplateRepository.save(smsTemplate);
        }else {
            ParamSmsTemplate byId = paramSmsTemplateRepository.getById(dto.getId());
            if(byId != null){
                smsTemplate.setRecVersion(byId.getRecVersion());
                paramSmsTemplateRepository.updateById(smsTemplate);
            }
        }
        return BaseResult.ok(null ,"保存成功");
    }
}
